﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Advance.Mvc.Models;
using Advanced.Domain.Core;
using IdentityServer4;
using IdentityServer4.Services;
using IdentityServer4.Test;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;

namespace Advance.Mvc.Controllers
{
    public class AccountController : Controller
    {
        private readonly SignInManager<ApplicationUser> _signManager;
        private readonly UserManager<ApplicationUser> _userManager;
        private readonly IIdentityServerInteractionService _interactionService;
        //private readonly TestUserStore _userStore;
        //public AccountController(TestUserStore userStore)
        //{
        //    this._userStore = userStore;
        //}
        public AccountController(SignInManager<ApplicationUser> signManager
            , UserManager<ApplicationUser> userManager
            , IIdentityServerInteractionService interactionService)
        {
            _signManager = signManager;
            _userManager = userManager;
            _interactionService = interactionService;
        }
        public IActionResult Login(string returnUrl = null)
        {
            ViewData["returnUrl"] = returnUrl;
            return View();
        }
        [HttpPost]
        public async Task<IActionResult> Login(LoginVm loginVm, string returnUrl = null)
        {
            ViewData["returnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                //var user = _userStore.FindByUsername(loginVm.UserName);
                var user = await _userManager.FindByEmailAsync(loginVm.Email);
                if (user == null)
                {
                    ModelState.AddModelError(nameof(user.Email), "Email not exists.");
                }
                else
                {
                    #region TestUserStore.
                    //if (_userStore.ValidateCredentials(loginVm.UserName, loginVm.Password))
                    //{
                    //    HttpContext.SignInAsync(user.SubjectId, user.Username, new AuthenticationProperties()
                    //    {
                    //        IsPersistent = true,
                    //        ExpiresUtc = DateTimeOffset.UtcNow.Add(TimeSpan.FromMinutes(30))
                    //    });
                    //}
                    //else
                    //{
                    //    ModelState.AddModelError(nameof(user.Username), "验证失败，请重试");
                    //} 
                    #endregion
                    var rt = user.Password.Equals(loginVm.Password);
                    //var rt = await _userManager.CheckPasswordAsync(user, loginVm.Password);
                    if (rt)
                    {
                        var prop = new AuthenticationProperties()
                        {
                            ExpiresUtc = DateTimeOffset.UtcNow.Add(TimeSpan.FromMinutes(30)),
                            IsPersistent = loginVm.Remember
                        };
                       await _signManager.SignInAsync(user, prop);
                    }
                    else
                    {
                        ModelState.AddModelError(nameof(user.Email), "验证失败，请重试");
                    }
                }

                return RedirectToLocal(returnUrl);
            }
            else
            {
                ModelState.AddModelError(nameof(loginVm.Email), "验证失败，请重试");
                return View();
            }
        }

        public IActionResult Logout()
        {
            //HttpContext.SignOutAsync();
            _signManager.SignOutAsync();
            return RedirectToAction(nameof(HomeController.Index), "Home");
        }

        private IActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl)&&_interactionService.IsValidReturnUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index","Consent");
            }
        }
    }
}